#!/bin/bash

# This script is screwy enough that it deserves some documentation.  To get
# statistics from the moblock daemon, you send it SIGUSR2 (man signal(7) for
# more info).  This causes moblock to output the statistics to
# /var/log/MoBlock.stats.  So this suicidal script sends SIGUSR2 to Moblock,
# scrapes the .stats file and sends SIGINT to it's self when it finds text
# that indicates the end of the report has been reached.
#
# It's screwy, but effective.

source /etc/conf.d/moblock
source /sbin/functions.sh

moblock_pidfile=/var/run/moblock.pid
stat_log_name=/var/log/MoBlock.stats

die () {
	eerror "$@"
	exit 1
}

read_stat_log() {
	while read; do
		if [ "${REPLY}" = "----------------------------------------" ]; then
			echo 
			einfo End of statistics
			echo
			kill -s INT $1
			return
		else
			echo "$REPLY"
		fi
	done
}

if [ ! -f "${moblock_pidfile}" ]; then
	die "MoBlock not running."
fi

tail --pid=$$ --lines=0 -f < ${stat_log_name} | read_stat_log $$ &

# Make sure tail starts before we send SIGUSR2
sleep 0.125
echo
einfo Requesting stats from MoBlock daemon...
echo

kill -s SIGUSR2 $(cat ${moblock_pidfile})

wait
